package cn.tedu.ivos.base.security;

import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户详情业务类，数据从数据库中获取到之后存入到CustomUserDetails中
 */
@Service
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    //loadUserByUsername从页面中获取到username
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("当前用户是:{}",username);
        //判断页面的用户名是否存在
        if(username==null)
            throw new UsernameNotFoundException("用户名不能为空");
        //根据用户名去数据库中查找对应的用户信息
        UserVO userVO = userMapper.selectByUsername(username);
        //判断userVO是否空
        if(userVO==null)
            throw new UsernameNotFoundException("用户不存在");
        //将userVO用户信息转存到CustomUserDetails对象中
        CustomUserDetails useInfo = new CustomUserDetails();
        //为userInfo赋值
        useInfo.setUsername(userVO.getUsername());
        useInfo.setPassword(userVO.getPassword());
        useInfo.setUserId(userVO.getId());
        //userInfo还有一个权限的属性，简单进行权限的初始化
        //给一个假的权限（test），就写一个名称就行，目前还没有具体的权限
        Set<GrantedAuthority> authoritySet = new HashSet<>();
        //创建GrantedAuthority对象
        GrantedAuthority authority = new SimpleGrantedAuthority("test");
        //将权限添加到权限集合中
        authoritySet.add(authority);
        //将权限集合赋值到userInfo中
        useInfo.setAuthorities(authoritySet);
        //千万要记得返回
        return useInfo;
    }
}
